/*
 * @Description: 定时任务
 * @Author: DSY
 * @Date: 2022-03-19 22:45:22
 * @LastEditors: dhlleo dhlleo@126.com
 * @LastEditTime: 2022-11-30 10:41:12
 */

import { defineComponent, computed, reactive, ref } from 'vue'
import { ElMessage } from 'element-plus'
import { cloneDeep, assign } from 'lodash-es'
import { QuartzJobModel } from '/@/api/system/model/quartzJobModel'
import { apiQuartzJobSave, apiQuartzJobUpdateById } from '/@/api/system/quartzJob'
import CronValidator from '/@/components/cron/validator'
import { log } from '/@/utils/log'


export default defineComponent({
  name: 'QuartzJobForm',
  components: {},
  emits: ['refreshTableData'],
  setup(props, { emit, expose }) {
    //////////////////////////////////////////////////
    // 属性
    //////////////////////////////////////////////////
    const dbFormRef = ref()
    const loading = ref(true)

    /**
     * 表单操作标记
     */
    const action = ref('add')

    /**
     * 显示弹框
     */
    const visible = ref(false)

    /**
     * 标题
     */
    const title = computed(() => {
      let rtn = ''
      switch (action.value) {
        case 'add':
          rtn = '新增'
          break
        case 'edit':
          rtn = '编辑'
          break
        default:
          rtn = '查看'
          break
      }
      return rtn
    })

    //////////////////////////////////////////////////
    // 表单
    //////////////////////////////////////////////////

    const defaultForm = {
      version: 0, // 版本号
      code: '', // 任务编码
      name: '', // 任务名称
      groupName: '', // 任务分组
      invokeTarget: '', // 调用目标字符串
      cronExpression: '', // 表达式
      misfirePolicy: '', // 计划策略(0=默认,1=立即触发执行,2=触发一次执行,3=不触发立即执行)
      concurrent: '', // 并发执行（1：允许；2：禁止）
      status: '', // 状态
      remark: '' // 备注
    }

    let dbForm = reactive<QuartzJobModel>(cloneDeep(defaultForm))

    //////////////////////////////////////////////////
    // 表单验证规则
    //////////////////////////////////////////////////

    /**
     * 表单验证规则
     */
    const rules = reactive({
      code: [
        {
          required: true,
          message: '请输入任务编码',
          trigger: 'blur'
        }
      ],
      name: [
        {
          required: true,
          message: '请输入任务名称',
          trigger: 'blur'
        }
      ],
      groupName: [
        {
          required: true,
          message: '请输入任务分组',
          trigger: 'blur'
        }
      ],
      invokeTarget: [
        {
          required: true,
          message: '请输入调用目标字符串',
          trigger: 'blur'
        }
      ],
      cronExpression: [
        {
          required: true,
          message: '请输入表达式',
          trigger: 'blur'
        },
        { validator: CronValidator }
      ],
      misfirePolicy: [
        {
          required: true,
          message: '请选择计划策略',
          trigger: 'blur'
        }
      ],
      concurrent: [
        {
          required: true,
          message: '请选择并发执行',
          trigger: 'blur'
        }
      ],
      status: [
        {
          required: true,
          message: '请选择状态',
          trigger: 'blur'
        }
      ],
      remark: [
        {
          required: false,
          message: '请输入备注',
          trigger: 'blur'
        }
      ]
    })

    //////////////////////////////////////////////////
    // 函数
    //////////////////////////////////////////////////

    /**
     * 打开弹框
     */
    function handleOpen(actionParam: string, rowParam?: QuartzJobModel) {
      visible.value = true
      loading.value = false
      action.value = actionParam
      if (['edit', 'view'].indexOf(actionParam) > -1 && rowParam) {
        assign(dbForm, cloneDeep(rowParam))
      }
    }

    /**
     * 关闭弹框
     */
    function handleClose() {
      assign(dbForm, cloneDeep(defaultForm))
      visible.value = false
    }

    /**
     * 提交表单
     */
    function handleSubmit(isContinue: boolean) {
      dbFormRef.value.validate((valid: boolean) => {
        if (valid) {
          if (action.value === 'add') {
            addFun(isContinue)
          } else {
            editFun()
          }
        } else {
          log.warn('定时任务', '表单校验失败')
        }
      })
    }

    /**
     * 新增
     * @param isContinue 是否新增并继续
     */
    function addFun(isContinue: boolean) {
      loading.value = true
      apiQuartzJobSave(dbForm)
        .then((result) => {
          if (result?.success) {
            ElMessage.success(result.message)

            handleReset(!isContinue)
          } else {
            ElMessage.error(result?.message)
          }
        })
        .catch(() => {})
        .finally(() => {
          loading.value = false
        })
    }

    /**
     * 编辑
     * @returns
     */
    function editFun() {
      loading.value = true
      apiQuartzJobUpdateById(dbForm)
        .then((result) => {
          if (result?.success) {
            ElMessage.success(result.message)

            handleReset(true)
          } else {
            ElMessage.error(result?.message)
          }
        })
        .catch(() => {})
        .finally(() => {
          loading.value = false
        })
    }

    /**
     * 重置表单
     * @param isClosed 是否关闭弹框
     */
    function handleReset(isClosed: boolean) {
      assign(dbForm, cloneDeep(defaultForm))
      if (isClosed) {
        emit('refreshTableData')
        visible.value = false
      }
    }

    //////////////////////////////////////////////////
    // cron 表达式
    //////////////////////////////////////////////////

    const cronRef = ref()
    const cron = reactive({
      visible: false,
      cronExpression: ''
    })

    /**
     * corn打开
     */
    function handleCronOpen() {
      cron.visible = true
      nextTick(() => {
        cron.cronExpression = dbForm.cronExpression
      })
    }

    /**
     * corn关闭
     */
    function handleCronClose() {
      cron.visible = false
    }

    /**
     * corn确认
     */
    function handleCronSubmit() {
      cron.visible = false
      dbForm.cronExpression = cron.cronExpression
    }

    /**
     * 暴露函数
     */
    expose({ handleOpen })

    return {
      loading,
      visible,
      action,
      title,
      dbFormRef,
      dbForm,
      rules,
      handleOpen,
      handleClose,
      handleSubmit,
      handleReset,
      cronRef,
      cron,
      handleCronClose,
      handleCronSubmit,
      handleCronOpen
    }
  }
})
